#! /usr/bin/env python
#coding=utf8

import urllib
import urllib2
import cookielib
import base64
import re
import json
import hashlib
from vavava.base import OBase
from vavava.httpclient import HttpClient
from vavava.util import LogAdapter,reg_helper

LOGIN_POSTDATA = {
    'entry': 'weibo',
    'gateway': '1',
    'from': '',
    'savestate': '7',
    'userticket': '1',
    'ssosimplelogin': '1',
    'vsnf': '1',
    'vsnval': '',
    'su': '',
    'service': 'miniblog',
    'servertime': '',
    'nonce': '',
    'pwencode': 'wsse',
    'sp': '',
    'encoding': 'UTF-8',
    'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
    'returntype': 'META'
}

class FetcherSina(OBase):
    def __init__(self,user,password,log=None):
        OBase.__init__(self,name="sina")
        self.__log = LogAdapter(log)
        self.__http = HttpClient()
        self.__http.EnableCookieSupport()
        self.__user = user
        self.__password = password
        self.curr_html = ""
        self.is_login = False
        self.user_uniqueid = ""
        self.__base_url = "http://weibo.com/"
        self.charset = "utf-8"
        self.content_list = []

    def __get_servertime(self):
        url = 'http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=dW5kZWZpbmVk&client=ssologin.js(v1.3.18)&_=1329806375939'
        data = self.__http.Get(url)
        p = re.compile('\((.*)\)')
        json_data = p.search(data).group(1)
        data = json.loads(json_data)
        servertime = str(data['servertime'])
        nonce = data['nonce']
        return servertime, nonce

    @staticmethod
    def __get_pwd(pwd, servertime, nonce):
        pwd1 = hashlib.sha1(pwd).hexdigest()
        pwd2 = hashlib.sha1(pwd1).hexdigest()
        pwd3_ = pwd2 + servertime + nonce
        pwd3 = hashlib.sha1(pwd3_).hexdigest()
        return pwd3

    @staticmethod
    def __get_user(username):
        username_ = urllib.quote(username)
        username = base64.encodestring(username_)[:-1]
        return username

    def login(self):
        url = 'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.3.18)'
        try:
            servertime, nonce = self.__get_servertime()
            #global LOGIN_POSTDATA
            LOGIN_POSTDATA['servertime'] = servertime
            LOGIN_POSTDATA['nonce'] = nonce
            LOGIN_POSTDATA['su'] = FetcherSina.__get_user(self.__user)
            LOGIN_POSTDATA['sp'] = FetcherSina.__get_pwd(self.__password, servertime, nonce)
            html_text = self.__http.Post(url,LOGIN_POSTDATA)
            p = re.compile('location\.replace\(\'(.*?)\'\)')
            login_url = p.search(html_text).group(1)
            #print login_url
            data = self.__http.Get(login_url)
            self.curr_html = data #data.decode(self.charset)
            self.is_login = True
            tmp = reg_helper(self.curr_html,r"\(([^\)]*)\)")[0]
            data = json.loads(tmp,self.charset)
            self.user_uniqueid = data["userinfo"]["uniqueid"]
            url = self.__base_url + "u/" + self.user_uniqueid + data["userinfo"]["userdomain"]
            #data = self.__http.Get(url)
            #self.curr_html = data.decode(self.charset)
        except Exception as e:
            self.__log.exception(e)

    def get_follow(self):
        url = self.__base_url + self.user_uniqueid + "/follow?leftnav=1&wvr=3.6"
        self.__http.header_refer_ = url
        data = self.__http.Get(url)
        self.curr_html = data.decode(self.charset)
        datas = reg_helper(self.curr_html,r"<script>\s*STK && STK.pageletM && STK.pageletM.view\((.*?)\)\s*</script>")
        data_list = []
        for data in datas:
            data_list.append(json.loads(data))
        for html in data_list:
            if "html" in html:
                self.content_list.append(html["html"])
        print len(data_list)


if __name__ == "__main__":
    sina = FetcherSina("pascal.for.gengine@gmail.com", "123123123")
    sina.login()
    if sina.is_login:
        print "ok"
        sina.get_follow()
        #f = open(r"C:\Users\vavava\Desktop\html.html","w")
        #f.write(sina.curr_html)
        #f.close()
        f = open(r"C:\Users\vavava\Desktop\data.txt","w")
        f.writelines(sina.content_list)
        f.close()
    else:
        print "no"